package com.jjh.springframework.test.bean;

import com.jjh.springframework.bean.factory.FactoryBean;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.HashMap;

/**
 * ProxyBeanFactory
 *
 * @author jjh
 * @date 2021/07/05
 **/
public class ProxyBeanFactory implements FactoryBean<IUserDao> {
    @Override
    public IUserDao getObject() throws Exception {
        InvocationHandler handler = (proxy, method, args) ->{
            // 代理方法
            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put("10001", "jjh");
            hashMap.put("10002", "gsh");
            hashMap.put("10003", "lzg");

            return "你被代理了" + method.getName() + ": " + hashMap.get(args[0]);
        };

        IUserDao iUserDao = (IUserDao) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[]{IUserDao.class}, handler);
        return iUserDao;
    }

    @Override
    public Class<IUserDao> getObjectType() {
        return IUserDao.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}
